<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use app\common\library\SimplePermission;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 管理员权限管理
 */
class AdminPermission extends Backend
{
    /**
     * AdminPermission模型对象
     * @var \app\admin\model\Admin
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Admin;
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自定义
     * 如果需要自定义，请复制application/admin/library/traits/Backend.php中对应的方法来修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                // 获取管理员权限
                $permission = SimplePermission::instance();
                $permissions = $permission->getAdminPermissions($row->id);
                $row->permissions = $permissions;
                $row->permission_count = count($permissions);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 设置权限
     */
    public function setPermissions($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            \think\Log::info('PC后台权限设置 - 接收到的参数: ' . json_encode($params));
            
            if ($params) {
                try {
                    $permission = SimplePermission::instance();
                    
                    // 获取所有可用权限
                    $allPermissions = $permission->getAllPermissions();
                    
                    // 处理权限数据
                    $formattedPermissions = [];
                    if (isset($params['permissions']) && is_array($params['permissions'])) {
                        \think\Log::info('PC后台权限设置 - 权限数组: ' . json_encode($params['permissions']));
                        
                        // 创建模块ID到模块名称的映射
                        $moduleMapping = [
                            '1' => 'order_manage',
                            '2' => 'allocation_manage', 
                            '3' => 'report_manage',
                            '4' => 'active_report_manage',
                            '5' => 'production_plan_manage',
                            '6' => 'product_manage',
                            '7' => 'model_manage',
                            '8' => 'process_manage',
                            '9' => 'admin_manage'
                        ];
                        
                        foreach ($params['permissions'] as $permissionKey) {
                            if (strpos($permissionKey, '/') !== false) {
                                list($moduleId, $action) = explode('/', $permissionKey, 2);
                                if (isset($moduleMapping[$moduleId])) {
                                    $module = $moduleMapping[$moduleId];
                                    $formattedPermissions[] = [
                                        'module' => $module,
                                        'action' => $action,
                                        'granted' => true
                                    ];
                                }
                            }
                        }
                        
                        \think\Log::info('PC后台权限设置 - 格式化后的权限: ' . json_encode($formattedPermissions));
                    } else {
                        \think\Log::info('PC后台权限设置 - 没有找到权限数据或权限数据不是数组');
                    }
                    
                    // 设置权限
                    $result = $permission->setAdminPermissions($ids, $formattedPermissions);
                    
                    if ($result) {
                        $this->success('权限设置成功');
                    } else {
                        $this->error('权限设置失败');
                    }
                } catch (Exception $e) {
                    $this->error('权限设置失败：' . $e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        // 获取当前管理员的权限
        $permission = SimplePermission::instance();
        $currentPermissions = $permission->getAdminPermissions($ids);
        $allPermissions = $permission->getAllPermissions();

        $this->view->assign("row", $row);
        $this->view->assign("currentPermissions", $currentPermissions);
        $this->view->assign("allPermissions", $allPermissions);
        return $this->view->fetch();
    }

    /**
     * 获取所有权限列表（AJAX）
     */
    public function getAllPermissions()
    {
        if ($this->request->isAjax()) {
            try {
                $permission = SimplePermission::instance();
                $permissions = $permission->getAllPermissions();
                $this->success('获取成功', $permissions);
            } catch (Exception $e) {
                $this->error('获取权限列表失败：' . $e->getMessage());
            }
        }
        $this->error('非法请求');
    }

    /**
     * 获取管理员权限（AJAX）
     */
    public function getAdminPermissions()
    {
        if ($this->request->isAjax()) {
            $adminId = $this->request->post('admin_id');
            if (!$adminId) {
                $this->error('管理员ID不能为空');
            }
            
            try {
                $permission = SimplePermission::instance();
                $permissions = $permission->getAdminPermissions($adminId);
                $this->success('获取成功', $permissions);
            } catch (Exception $e) {
                $this->error('获取管理员权限失败：' . $e->getMessage());
            }
        }
        $this->error('非法请求');
    }
}
